package com.pattern.interceptor;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Mr.yuan
 * @version v1.0
 * @date 2019/7/25 15:06
 **/
public class InterceptorPattern {


    public static void main(String[] args) {
        InterceptorManager manager = new InterceptorManager(new Target());
        manager.setInterceptor(new AuthenticationInterceptor());
        manager.setInterceptor(new AuthorizationInterceptor());
        Client client = new Client();
        client.setInterceptorManager(manager);
        client.sendRequest("go");
    }

    private static class Client {

        private InterceptorManager manager;

        void setInterceptorManager(InterceptorManager manager) {
            this.manager = manager;
        }

        void sendRequest(String request) {
            manager.interceptorRequest(request);
        }
    }
    private static class InterceptorManager {
        private InterceptorChain chain;
        InterceptorManager(Target target) {
            chain = new InterceptorChain();
            chain.setTarget(target);
        }
        private void setInterceptor(Interceptor interceptor){
            chain.addInterceptor(interceptor);
        }

        private void interceptorRequest(String request){
            chain.execute(request);
        }
    }

    private static class InterceptorChain {
        private List<Interceptor> interceptors = new ArrayList<>();
        private Target target;

        void setTarget(Target target) {
            this.target = target;
        }

        void addInterceptor(Interceptor interceptor) {
            interceptors.add(interceptor);
        }
        private void execute(String request) {
            for (Interceptor interceptor : interceptors) {
                interceptor.execute(request);
            }
            target.execute(request);
        }
    }
    private static class Target {
        void execute(String request){
            System.out.println("target execute "+request);
        }
    }
    private interface Interceptor{
        void execute(String request);
    }
    private static class AuthenticationInterceptor implements Interceptor{
        @Override
        public void execute(String request) {
            System.out.println("authentication request "+request);
        }
    }
    private static class AuthorizationInterceptor implements Interceptor{
        @Override
        public void execute(String request) {
            System.out.println("authorization request "+request);
        }
    }


}
